package es.udc.emarketapp.emarket.model.shippingFacade.actions;

import java.sql.Connection;
import java.util.List;

import es.udc.emarketapp.emarket.model.shipping.dao.SQLShippingDAO;
import es.udc.emarketapp.emarket.model.shipping.dao.SQLShippingDAOFactory;
import es.udc.emarketapp.emarket.model.shippingFacade.ShippingFacade;
import es.udc.emarketapp.emarket.model.shippingFacade.vo.ShippingsCountryVO;
import es.udc.emarketapp.emarket.model.shippingFacade.vo.ShippingsSellerChunkVO;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.NonTransactionalPlainAction;
import java.util.ArrayList;
import java.util.Iterator;

public class CountriesRatesBySellerAction implements NonTransactionalPlainAction {

    private String idSeller;
    private String language;
    private int startIndex;
    private int count;

    public CountriesRatesBySellerAction(String idSeller, String language,
            int startIndex, int count) {

        this.idSeller = idSeller;
        this.language = language;
        this.startIndex = startIndex;
        this.count = count;

    }

    public Object execute(Connection connection)
            throws InternalErrorException {


        ShippingFacade shippingFacade = new ShippingFacade();
        SQLShippingDAO shippingDAO = SQLShippingDAOFactory.getDAO();


        List<String> countries =
                shippingDAO.findCountriesBySeller(connection, idSeller,
                startIndex, count);


        List<ShippingsCountryVO> listShippingsCountry = new ArrayList();


        if (!language.equals("es")) {
            language = "en";
        }

        Iterator iter = countries.iterator();
        while (iter.hasNext()) {

            ShippingsCountryVO shippingsCountry =
                    shippingFacade.findCountryRates(idSeller,
                    (String) iter.next(), language);

            listShippingsCountry.add(shippingsCountry);
        }

        boolean existMoreCountries = countries.size() == (count + 1);

        if (existMoreCountries) {
            countries.remove(countries.size() - 1);
        }

        return new ShippingsSellerChunkVO(listShippingsCountry, existMoreCountries);

    }
}
